package com.zc.edu.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zc.edu.entity.Subject;
import com.zc.edu.entity.excel.SubjectData;
import com.zc.edu.service.SubjectService;

import java.util.Map;

public class SubjectExcelListen extends AnalysisEventListener<SubjectData> {
	public SubjectService subjectService;

	public SubjectExcelListen() {
	}

	public SubjectExcelListen(SubjectService subjectService) {
		this.subjectService = subjectService;
	}

	@Override
	public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
		if (subjectData == null) {
			throw new IllegalStateException("数据为空");
		}
        // 判断一级分类是否重复
		Subject oneSubject = this.existSubject(subjectData.getOneSubjectName(), "0");
		if (oneSubject == null) {
			oneSubject = new Subject();
			oneSubject.setParentId("0");
			oneSubject.setTitle(subjectData.getOneSubjectName());
			boolean save = subjectService.save(oneSubject);
		}
		String oneSubId = oneSubject.getId();
		// 判断二级分类
		Subject twoSubject = this.existSubject(subjectData.getTwoSubjectName(), oneSubId);
		if (twoSubject == null) {
			twoSubject = new Subject();
			twoSubject.setParentId(oneSubId);
			twoSubject.setTitle(subjectData.getTwoSubjectName());
			subjectService.save(twoSubject);
		}

	}

	// 判断一级分类不能重复添加
	private Subject existSubject(String name, String parentId) {
		QueryWrapper<Subject> wrapper = new QueryWrapper<>();
		wrapper.eq("title", name).eq("parent_id", parentId);
		Subject subject = subjectService.getOne(wrapper);
		return subject;
	}

	@Override
	public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {

	}
}
